package com.itranswarp.learnjava.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.JsonProcessingException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import com.itranswarp.learnjava.bean.SignInBean;
import com.itranswarp.learnjava.bean.UpdateBean;
import com.itranswarp.learnjava.bean.UpdateBean;
import com.itranswarp.learnjava.bean.Page;
import com.itranswarp.learnjava.bean.User;
import com.itranswarp.learnjava.bean.PageResult;

import com.itranswarp.learnjava.framework.GetMapping;
import com.itranswarp.learnjava.framework.ModelAndView;
import com.itranswarp.learnjava.framework.PostMapping;

import com.itranswarp.learnjava.utils.Token;
import com.itranswarp.learnjava.utils.Response;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itranswarp.learnjava.dao.UserDAO;
import java.util.ArrayList;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Objects;

public class UserController {

    public static void writeJson(HttpServletResponse response, Object obj) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_OK); // ✅ 明确设置 200
        PrintWriter pw = response.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        pw.write(mapper.writeValueAsString(obj));
        pw.flush();
    }

    public static boolean validateUser(HttpSession session){
        User user = (User) session.getAttribute("user");
        return user != null;
    }


    @GetMapping("/signin")
    public ModelAndView signin() {
        return new ModelAndView("/signin.html");
    }

    @PostMapping("/api/signin")
    public ModelAndView doSignin(SignInBean bean, HttpServletResponse response, HttpSession session) throws IOException, SQLException {
        UserDAO userDAO = new UserDAO();
        User user = userDAO.addUser(bean.username, bean.password, bean.phone, bean.email);
        if(!Objects.isNull(user)){
            writeJson(response, new Response<>(200, "", user));
        } else {
            writeJson(response, new Response<>(204, "Bad userName or password", null));
        }
        return null;
    }

    @PostMapping("/api/login")
    public ModelAndView doLogin(SignInBean bean, HttpServletResponse response, HttpSession session) throws IOException, SQLException {
        UserDAO userDAO = new UserDAO();
        User user = userDAO.getUser(bean.username, bean.password);
        if(!Objects.isNull(user)){
            session.setAttribute("user", user);
            System.out.println("登录了");
            writeJson(response, new Response<>(200, "", user));
        } else {
            writeJson(response, new Response<>(204, "用户名密码错误", null));
        }
        return null;
    }

    @PostMapping("/api/updateUser")
    public ModelAndView doUpdateUser(UpdateBean bean, HttpServletResponse response, HttpSession session) throws IOException, SQLException {
        UserDAO userDAO = new UserDAO();
        User sessionUser = (User) session.getAttribute("user");
        User user = userDAO.updateUser(bean.id, bean.username, bean.phone, bean.email);
        if(!Objects.isNull(user)){
            session.setAttribute("user", user);
            writeJson(response, new Response<>(200, "", user));
        } else {
            writeJson(response, new Response<>(204, "修改失败", null));
        }
        return null;
    }

    @PostMapping("/api/remove")
    public ModelAndView doRemoveUser(UpdateBean bean, HttpServletResponse response, HttpSession session) throws IOException, SQLException {
        if(!validateUser(session)){
            writeJson(response, new Response<>(204, "请登录", null));
        }

        UserDAO userDAO = new UserDAO();
        User sessionUser = (User) session.getAttribute("user");
        boolean isRemoved = userDAO.removeUser(bean.id);
        if(isRemoved){
            writeJson(response, new Response<>(200, "", null));
        } else {
            writeJson(response, new Response<>(204, "删除失败", null));
        }
        return null;
    }

    @GetMapping("/login")
    public ModelAndView login() {
        return new ModelAndView("/login.html");
    }

    @GetMapping("/home")
    public ModelAndView home() {
        return new ModelAndView("/home.html");
    }

    @GetMapping("/users")
    public ModelAndView users(int page, HttpSession session) throws JsonProcessingException {
        if(!validateUser(session)){
            return new ModelAndView("redirect:/signin");
        }
        UserDAO userDAO = new UserDAO();
        int offset = page-1;
        PageResult<User> result = userDAO.getAllUsers(offset>0?offset:0, 10);
        ObjectMapper mapper = new ObjectMapper();
        return new ModelAndView("/users.html", "result", mapper.writeValueAsString(result));
    }

    @GetMapping("/signout")
    public ModelAndView signout(HttpSession session) {
        session.removeAttribute("user");
        return new ModelAndView("redirect:/");
    }

    @GetMapping("/user/profile")
    public ModelAndView profile(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return new ModelAndView("redirect:/signin");
        }
        return new ModelAndView("/profile.html", "user", user);
    }
}
